﻿using B.S.GridManage.Api.Write.DTOs;
using B.S.GridManage.ErrorCode;
using Consul;
using Microsoft.EntityFrameworkCore.Metadata;

namespace B.S.GridManage.Api.Write.InnerApi
{
    public class ServiceDiscovery
    {
        private readonly IConsulClient consulClient;
        private readonly HttpClient  httpClient;

        /// <summary>
        /// 服务发现,注入相关资源
        /// </summary>
        /// <param name="consulClient">consul注册中心</param>
        /// <param name="facotry">IHttpClientFactory 工厂</param>
        public ServiceDiscovery(IConsulClient consulClient,IHttpClientFactory facotry)
        { 
            this.consulClient = consulClient; //注入onsul注册中心
            this.httpClient = facotry.CreateClient("");//使用工厂生成 httpClient的实例
        }

        /// <summary>
        /// 根据服务名 找到实例
        /// </summary>
        /// <param name="serviceName">服务名</param>
        /// <returns>实例url</returns>
        public async Task< string> GetUrl(string serviceName) {
         var service = await consulClient.Health.Service(serviceName);//根据服务名从consul注册中心中拿到服务   
            var length = service.Response.Length;//查看一共有多少个实例

            var index = new Random().Next(0, length-1); //生成一个0到实例总数之间的随机数
            
            var instance = service.Response[index]; //根据下标取到一个实际的实例

            var port = instance.Service.Port;
            var ip = instance.Service.Address;

            return $"http://{ip}:{port}";
        }

        public async Task<ApiPaging<UnitGridDto>> GetUnitGridPages(string url,string api) {


            Uri uri= new Uri(url+api); //拼接访问地址
            var res =await httpClient.GetAsync(uri); //发起get请求
            res.EnsureSuccessStatusCode();//设置响应状态为成功200
            return  await res.Content.ReadFromJsonAsync<ApiPaging<UnitGridDto>>();//把响应结果转换为响应包装
        }
    }
}
